#!/usr/bin/python 
# @Time  : 2020/5/20 17:39
# @Author: LOUIE
# @Desc  : 数据加载
import yaml
import os
import re
import config
from utils.parser import parse_data
from utils.logger import log


def load_folder(folder):
    log.info("Loading folder ...")
    if isinstance(folder, (list, set)):
        files = []
        for path in set(folder):
            files.extend(load_folder(path))

        return files

    if not os.path.exists(folder):
        return []

    filepath_list = []

    for dirpath, dirnames, filenames in os.walk(folder):
        filenames_list = []

        for filename in filenames:
            if not filename.endswith(('.yml', '.yaml', '.json')):
                continue

            filenames_list.append(filename)

        for filename in filenames_list:
            filepath = os.path.join(dirpath, filename)
            filepath_list.append(filepath)

    return filepath_list


def load_yaml(filepath):
    """
    读取指定YAML文件数据
    :param filepath:
    :return:
    """
    if os.path.exists(filepath):
        filepath = filepath
    else:
        filepath = os.path.join(config.CASE_DIR, filepath)

    # log.info(f'Loading yaml : {filepath}')
    with open(filepath, encoding='utf-8') as file:
        try:
            stream = yaml.safe_load(file)
        except yaml.YAMLError as ex:
            raise ex

        return stream


def load_env_variables(config_var):
    env_var = config_var.get(config.ENV.lower(), {})
    if env_var:
        env_variables = {}
        env_variables.update(env_var)

    log.info("Parser env variables: {}".format(env_var))
    return env_variables


url_regex = re.compile(r"^https?://", re.I)


def build_url(config_var, path, variables_pool):
    """
    合并URL
    :param base_url:
    :param path:
    :return:
    """
    base_url = config_var.get(config.ENV)
    base_url = base_url.get('base_url', 'url missd')
    if url_regex.match(path):
        path = path
    elif base_url:
        path = "{}/{}".format(base_url.rstrip("/"), path.lstrip("/"))
    else:
        raise ValueError(f"{config.ENV} base_url missed !")
    return parse_data(path, variables_pool)


def build_method(method: str):
    if not method:
        raise FileNotFoundError('Method not found !')
    method_list = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]
    if method.upper() in method_list:
        return method.upper()
    else:
        error_msg = f"Invalid HTTP method: {method.upper()} !"
        log.error(error_msg)
        raise Exception(error_msg)


def build_request(request: dict, variables_pool: dict):
    if not request:
        return request
    else:
        return parse_data(request, variables_pool)


def build_validator(validator: dict, variables_pool: dict):
    if not validator:
        return None
    else:
        return parse_data(validator, variables_pool)


if __name__ == '__main__':
    filepath_list = load_folder(config.CASE_DIR)
    print(filepath_list)
